package gis

import (
	"dgo/goutils/utils"
)

type NmeaDecoderV0 struct {
	nmeaPack *utils.SEBufPack

	OnNmea func(sender *NmeaDecoderV0, nmea string)
}

func NewNmeaDecoderV0() *NmeaDecoderV0 {
	rval := &NmeaDecoderV0{}
	return rval
}

func (this *NmeaDecoderV0) InputByte(v byte) {
	if this.nmeaPack == nil {
		this.nmeaPack = utils.NewSEBufPack(1024)
		this.nmeaPack.SetSEBuf([]byte("$"), []byte("*"))
	}

	if this.nmeaPack.TagCounter > 0 {
		this.nmeaPack.ForceAppendByte(v)
		this.nmeaPack.TagCounter++
		if this.nmeaPack.TagCounter == 3 {
			tmpBuf := this.nmeaPack.GetRawBuf()
			nmeaStr := utils.TrimUtf8Str(string(tmpBuf), 1204)
			if CheckNMEAIsOK(nmeaStr) {
				if this.OnNmea != nil {
					this.OnNmea(this, nmeaStr)
				}
			}

			this.nmeaPack.TagCounter = 0
		}
	} else {
		r := this.nmeaPack.InputByte(v)
		if r == 1 {
			this.nmeaPack.TagCounter = 1
		} else if r < 0 {
			this.nmeaPack.TagCounter = 0
		}
	}
}
